<template>
  <div class="permission">
    <el-card>
      <!-- 按钮 -->
      <div class="box">
        <el-button @click="openAdd(1, 0)" type="primary" size="mini"
          >添加菜单</el-button
        >
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" row-key="id">
        <el-table-column prop="name" label="菜单名称"> </el-table-column>
        <el-table-column prop="code" label="权限标识"> </el-table-column>
        <el-table-column prop="description" label="描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button
              @click="openAdd(2, row.id)"
              v-if="row.type === 1"
              type="text"
              >添加权限</el-button
            >
            <el-button type="text">查看api权限</el-button>
            <el-button @click="openEdit(row.id)" type="text">查看</el-button>
            <el-button @click="del(row.id)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <aded
      ref="aded"
      @update="getAllPermission"
      :adedShow.sync="adedShow"
    ></aded>
  </div>
</template>

<script>
import { getAllPermissionApi, delSysPermissionApi } from '@/api/permission'
// 导入组件
import aded from './components/aded.vue'
export default {
  data () {
    return {
      tableData: [],
      // 控制新增 & 编辑面板的显示与隐藏
      adedShow: false
    }
  },
  methods: {
    // 打开新增面板
    openAdd (type, pid) {
      // type：要新增的级别
      // pid：要新增的权限的父权限的 id
      this.adedShow = true
      this.$refs.aded.setProp(type, pid)
    },
    openEdit (id) {
      // 打开编辑面板
      this.adedShow = true
      // 根据 id 得到编辑面板中的权限数据
      this.$refs.aded.getPermissionById(id)
    },
    // 删除权限
    async del (id) {
      try {
        // 询问是否删除
        await this.$confirm('是否删除当前权限')
        // 删除数据
        await delSysPermissionApi(id)
        // 提示
        this.$message.success('删除成功')
        // 更新数据
        this.getAllPermission()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 得到所有的权限数据
    async getAllPermission () {
      const res = await getAllPermissionApi()
      this.tableData = this.turnData(res, '0')
    },
    // 将数据转换为树状态结构
    turnData (arr, str) {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.turnData(arr, item.id)
          return true
        }
        return false
      })
    }
  },
  created () {
    this.getAllPermission()
  },
  components: {
    aded
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
  .box {
    text-align: right;
  }
}
</style>
